from flask import Flask, jsonify, request, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
from models import UserModel
from flask_cors import CORS
from extensions import init_mysql
app = Flask(__name__)
CORS(app, supports_credentials=True)

# 保持原有配置不变
# MySQL 配置
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '23'
app.config['MYSQL_DB'] = 'sxf'

# 初始化数据库
mysql = init_mysql(app)
user_model = UserModel(mysql)
# 登录接口
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, password))
    account = cursor.fetchone()

    if account:
        session['loggedin'] = True
        session['id'] = account['id']
        session['username'] = account['username']
        return jsonify({
            'status': 'success',
            'message': '登录成功',
            'user': {
                'id': account['id'],
                'username': account['username']
            }
        })
    else:
        return jsonify({'status': 'error', 'message': '用户名/密码错误'}), 401

# 注册接口
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')

    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("SELECT * FROM accounts WHERE username LIKE %s", [username])
    account = cursor.fetchone()

    response = {'status': 'error'}
    if account:
        response['message'] = '用户已存在'
    elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
        response['message'] = '邮箱格式无效'
    elif not re.match(r'[A-Za-z0-9]+', username):
        response['message'] = '用户名只能包含字母和数字'
    elif not username or not password or not email:
        response['message'] = '请填写完整表单'
    else:
        cursor.execute('INSERT INTO accounts VALUES (NULL, %s, %s, %s)', (username, email, password))
        mysql.connection.commit()
        response['status'] = 'success'
        response['message'] = '注册成功'

    return jsonify(response)

# 获取用户信息
@app.route('/api/user')
def user_info():
    if 'loggedin' in session:
        return jsonify({
            'status': 'success',
            'user': {
                'id': session['id'],
                'username': session['username']
            }
        })
    return jsonify({'status': 'error', 'message': '未登录'}), 401

if __name__ == '__main__':
    app.run(debug=True)